<template>
  <div class="weekly-reports">
    <div class="header">
      <h3>周工作报告</h3>
      <div class="header-actions">
        <el-button type="primary" @click="openCreateDialog">
          <el-icon><Plus /></el-icon> 提交周报
        </el-button>
        <el-button type="success" @click="showAISummaryDialog = true">
          <el-icon><MagicStick /></el-icon> AI 总结生成
        </el-button>
        <el-button type="danger" @click="batchDelete" :disabled="selectedReports.length === 0">
          <el-icon><Delete /></el-icon> 批量删除 ({{ selectedReports.length }})
        </el-button>
        <el-button @click="toggleSelectAll">
          {{ selectedReports.length === weeklyReports.length && weeklyReports.length > 0 ? '取消全选' : '全选' }}
        </el-button>
      </div>
    </div>

    <!-- Loading State -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <!-- Empty State -->
    <div v-else-if="weeklyReports.length === 0" class="empty-state">
      <el-empty description="暂无周报数据" />
    </div>

    <!-- Reports Grid -->
    <el-row v-else :gutter="20" class="report-grid">
      <el-col 
        v-for="report in weeklyReports" 
        :key="report.id" 
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="8" 
        :xl="6"
      >
        <el-card 
          class="report-card" 
          :class="{ 'is-selected': selectedReports.includes(report.id) }"
          shadow="hover"
          @click.stop="toggleSelection(report.id)"
        >
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-checkbox 
                  :model-value="selectedReports.includes(report.id)"
                  @change="toggleSelection(report.id)"
                  @click.stop
                />
                <span class="report-date">{{ report.year }}年{{ report.month }}月 第{{ report.week }}周</span>
              </div>
              <el-tag type="success" size="small" effect="dark">已提交</el-tag>
            </div>
          </template>
          
          <div class="card-content">
            <div class="report-section">
              <div class="section-label"><el-icon><Trophy /></el-icon> 本周成就</div>
              <div class="section-text achievements" :class="{ 'empty': !report.achievements }">
                {{ report.achievements || '暂无成就记录' }}
              </div>
            </div>
            
            <div class="report-section">
              <div class="section-label"><el-icon><Warning /></el-icon> 遇到挑战</div>
              <div class="section-text challenges" :class="{ 'empty': !report.challenges }">
                {{ report.challenges || '暂无挑战记录' }}
              </div>
            </div>

            <div v-if="report.highlights" class="report-section ai-highlights">
              <div class="section-label"><el-icon><MagicStick /></el-icon> AI 亮点</div>
              <div class="section-text highlights">
                {{ report.highlights }}
              </div>
            </div>

            <!-- Linked Plan Section -->
            <div v-if="report.weekly_plan_id" class="report-section linked-plan">
              <div class="section-label">
                <el-icon><Link /></el-icon> 关联计划
              </div>
              <div class="plan-link" @click.stop="viewLinkedPlan(report)">
                <div class="plan-info">
                  <el-icon class="plan-icon"><Document /></el-icon>
                  <span class="plan-title">{{ report.plan_title || '关联计划' }}</span>
                </div>
                <el-icon class="arrow-icon"><ArrowRight /></el-icon>
              </div>
            </div>

            <div class="report-meta">
              <div class="meta-left">
                提交于 {{ formatDate(report.created_at) }}
              </div>
              <div class="meta-right">
                <el-tag v-if="report.weekly_plan_id" size="small" type="primary" effect="plain">
                  <el-icon style="margin-right: 2px;"><Link /></el-icon>
                  已关联计划
                </el-tag>
                <el-tag v-else size="small" type="info" effect="plain">
                  未关联计划
                </el-tag>
              </div>
            </div>
          </div>
          
          <div class="card-actions" @click.stop>
            <el-tooltip content="查看详情" placement="top">
              <el-button circle size="small" type="primary" @click="viewReport(report)">
                <el-icon><View /></el-icon>
              </el-button>
            </el-tooltip>

            <el-tooltip content="编辑周报" placement="top">
              <el-button circle size="small" type="warning" @click="editReport(report)">
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-tooltip>

            <el-tooltip content="生成AI总结" placement="top">
              <el-button circle size="small" type="success" @click="generateSummaryForReport(report)">
                <el-icon><MagicStick /></el-icon>
              </el-button>
            </el-tooltip>
            
            <el-tooltip content="删除周报" placement="top">
              <el-button circle size="small" type="danger" @click="deleteReport(report)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- Create/Edit Report Dialog - Modern Design -->
    <el-dialog
      v-model="showCreateDialog"
      :title="isEdit ? '编辑周报' : '提交周报'"
      width="750px"
      :close-on-click-modal="false"
      class="modern-dialog"
    >
      <el-form :model="reportForm" :rules="rules" ref="reportFormRef" label-position="top" class="modern-form">
        <!-- Date Selection with Calendar Picker -->
        <div class="form-section">
          <div class="section-header">
            <el-icon class="header-icon"><Calendar /></el-icon>
            <span>报告周期</span>
            <el-tag size="small" type="info" effect="plain">自动填充</el-tag>
          </div>
          <div class="auto-date-display">
            <div class="date-info">
              <el-icon><Calendar /></el-icon>
              <span class="date-text">{{ reportForm.year }}年{{ reportForm.month }}月 第{{ reportForm.week }}周</span>
            </div>
            <el-button 
              text 
              type="primary" 
              size="small"
              @click="showDatePicker = !showDatePicker"
            >
              {{ showDatePicker ? '收起' : '修改周期' }}
            </el-button>
          </div>
          <el-collapse-transition>
            <el-form-item v-if="showDatePicker" label="选择其他周期">
              <el-date-picker
                v-model="reportDate"
                type="week"
                format="YYYY 年第 ww 周"
                placeholder="选择周次"
                style="width: 100%"
                @change="handleDateChange"
                :clearable="false"
              />
            </el-form-item>
          </el-collapse-transition>
        </div>

        <!-- Weekly Plan Association Section -->
        <div class="form-section">
          <div class="section-header">
            <el-icon class="header-icon primary"><Link /></el-icon>
            <span>关联周计划</span>
            <el-tag size="small" type="info" effect="plain">可选</el-tag>
          </div>
          <el-alert
            v-if="!reportForm.weekly_plan_id"
            title="建议关联周计划"
            type="warning"
            description="关联周计划可以自动填充工作成就，并帮助追踪计划完成情况。"
            show-icon
            :closable="false"
            style="margin-bottom: 15px;"
          />
          <el-form-item label="选择关联计划">
            <el-select 
              v-model="reportForm.weekly_plan_id" 
              placeholder="选择本周的工作计划（可选）"
              clearable
              filterable
              style="width: 100%"
              :loading="loadingPlans"
              @focus="loadAvailablePlans"
            >
              <el-option :value="null" label="不关联计划">
                <span style="color: #909399;">📋 不关联任何计划</span>
              </el-option>
              <el-option
                v-for="plan in availablePlans"
                :key="plan.id"
                :value="plan.id"
                :label="plan.title"
              >
                <div style="display: flex; align-items: center; justify-content: space-between;">
                  <span style="display: flex; align-items: center;">
                    <el-tag size="small" type="info" style="margin-right: 8px;">第{{ plan.week }}周</el-tag>
                    <el-icon style="margin-right: 4px;"><Document /></el-icon>
                    {{ plan.title }}
                  </span>
                  <el-tag 
                    :type="plan.status === 'completed' ? 'success' : plan.status === 'in_progress' ? 'primary' : 'info'" 
                    size="small"
                  >
                    {{ getStatusText(plan.status) }}
                  </el-tag>
                </div>
              </el-option>
            </el-select>
            <div v-if="reportForm.weekly_plan_id && selectedPlanInfo" class="plan-preview">
              <div class="preview-header">
                <el-icon><InfoFilled /></el-icon>
                <span>关联计划预览</span>
              </div>
              <div class="preview-content">
                <p><strong>计划：</strong>{{ selectedPlanInfo.title }}</p>
                <p v-if="selectedPlanInfo.description"><strong>描述：</strong>{{ selectedPlanInfo.description }}</p>
              </div>
            </div>
          </el-form-item>
        </div>

        <!-- Achievements Section -->
        <div class="form-section">
          <div class="section-header">
            <el-icon class="header-icon success"><Trophy /></el-icon>
            <span>本周成就</span>
            <el-tag size="small" type="success" effect="plain">必填</el-tag>
          </div>
          <el-form-item prop="achievements">
            <el-input 
              v-model="reportForm.achievements" 
              type="textarea" 
              :rows="5"
              placeholder="请描述本周的主要成就和工作内容&#10;例如：&#10;• 完成了XX项目的核心功能开发&#10;• 解决了YY系统的性能问题，性能提升30%&#10;• 协助团队完成了ZZ需求的评审"
              show-word-limit
              maxlength="1000"
            />
          </el-form-item>
        </div>
        
        <!-- Challenges Section -->
        <div class="form-section">
          <div class="section-header">
            <el-icon class="header-icon warning"><Warning /></el-icon>
            <span>遇到挑战</span>
            <el-tag size="small" type="warning" effect="plain">必填</el-tag>
          </div>
          <el-form-item prop="challenges">
            <el-input 
              v-model="reportForm.challenges" 
              type="textarea" 
              :rows="4"
              placeholder="请描述遇到的挑战和问题&#10;例如：&#10;• 在XX功能开发中遇到技术难点&#10;• YY需求变更导致进度延迟&#10;• 需要更多的资源支持"
              show-word-limit
              maxlength="500"
            />
          </el-form-item>
        </div>
        
        <!-- Next Week Plan Section -->
        <div class="form-section">
          <div class="section-header">
            <el-icon class="header-icon primary"><Target /></el-icon>
            <span>下周计划</span>
            <el-tag size="small" type="primary" effect="plain">必填</el-tag>
          </div>
          <el-form-item prop="next_week_plan">
            <el-input 
              v-model="reportForm.next_week_plan" 
              type="textarea" 
              :rows="4"
              placeholder="请描述下周的工作计划&#10;例如：&#10;• 完成XX功能的测试和上线&#10;• 开始YY项目的需求分析&#10;• 优化ZZ系统的性能"
              show-word-limit
              maxlength="500"
            />
          </el-form-item>
        </div>
      </el-form>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="showCreateDialog = false" size="large">
            <el-icon><Close /></el-icon>
            取消
          </el-button>
          <el-button type="primary" @click="submitReport" :loading="submitting" size="large">
            <el-icon><Check /></el-icon>
            {{ isEdit ? '更新周报' : '提交周报' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- Report Details Dialog -->
    <el-dialog
      v-model="showDetailsDialog"
      title="周报详情"
      width="700px"
      class="report-dialog"
    >
      <div v-if="selectedReport" class="report-content">
        <div class="report-header">
          <div class="report-time">
            <el-icon><Calendar /></el-icon>
            {{ selectedReport.year }}年 {{ selectedReport.month }}月 第{{ selectedReport.week }}周
          </div>
          <el-tag type="success" effect="dark">已提交</el-tag>
        </div>

        <div class="report-section">
          <h4><el-icon><Trophy /></el-icon> 本周成就</h4>
          <div class="section-content">{{ selectedReport.achievements }}</div>
        </div>
        
        <div class="report-section">
          <h4><el-icon><Warning /></el-icon> 遇到挑战</h4>
          <div class="section-content">{{ selectedReport.challenges }}</div>
        </div>
        
        <div class="report-section">
          <h4><el-icon><Target /></el-icon> 下周计划</h4>
          <div class="section-content">{{ selectedReport.next_week_plan }}</div>
        </div>
        
        <div class="report-section ai-section" v-if="selectedReport.highlights || selectedReport.summary">
          <h4><el-icon><MagicStick /></el-icon> AI 智能总结 & 亮点</h4>
          <div class="ai-content">
            <div v-if="selectedReport.summary" class="ai-summary">
              <strong>工作总结：</strong>
              <p>{{ selectedReport.summary }}</p>
            </div>
            <div v-if="selectedReport.highlights" class="ai-highlights">
              <strong>核心亮点：</strong>
              <div class="highlight-text">{{ selectedReport.highlights }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- AI 总结生成对话框 -->
    <el-dialog
      v-model="showAISummaryDialog"
      title="AI 周报总结生成"
      width="600px"
    >
      <el-form :model="aiSummaryForm" label-width="100px">
        <el-form-item label="工作内容">
          <el-input 
            v-model="aiSummaryForm.workContent" 
            type="textarea" 
            :rows="6"
            placeholder="请详细描述本周的工作内容、完成的任务、遇到的问题等..."
          />
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-input 
            v-model="aiSummaryForm.timeframe" 
            placeholder="例如：2024-01-W1"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAISummaryDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="generateAISummary" 
          :loading="generatingSummary"
        >
          <el-icon><MagicStick /></el-icon>
          生成周报总结
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted, computed } from 'vue'
import axios from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useAuthStore } from '../stores/auth'
import { Plus, MagicStick, Calendar, Trophy, Warning, Aim as Target, Delete, View, Edit, Check, Close, Link, Document, InfoFilled, ArrowRight } from '@element-plus/icons-vue'

export default {
  name: 'WeeklyReports',
  components: {
    Plus,
    MagicStick,
    Calendar,
    Trophy,
    Warning,
    Target,
    Delete,
    View,
    Edit,
    Check,
    Close,
    Link,
    Document,
    InfoFilled,
    ArrowRight
  },
  setup() {
    const authStore = useAuthStore()
    const weeklyReports = ref([])
    const selectedReports = ref([])
    const loading = ref(false)
    const showCreateDialog = ref(false)
    const showDetailsDialog = ref(false)
    const showAISummaryDialog = ref(false)
    const selectedReport = ref(null)
    const submitting = ref(false)
    const generatingSummary = ref(false)
    const isEdit = ref(false)
    const editingId = ref(null)
    const reportDate = ref(new Date())
    const showDatePicker = ref(false)
    
    // Plan association states
    const availablePlans = ref([])
    const loadingPlans = ref(false)
    
    const reportForm = ref({
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      week: getWeekOfMonth(new Date()),
      achievements: '',
      challenges: '',
      next_week_plan: '',
      weekly_plan_id: null  // New field for plan association
    })

    const aiSummaryForm = ref({
      workContent: '',
      timeframe: `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}-W${getWeekOfMonth(new Date())}`
    })
    
    const reportFormRef = ref()
    
    const rules = {
      achievements: [{ required: true, message: '请填写本周成就', trigger: 'blur' }],
      challenges: [{ required: true, message: '请填写遇到的挑战', trigger: 'blur' }],
      next_week_plan: [{ required: true, message: '请填写下周计划', trigger: 'blur' }]
    }

    // Computed property for selected plan info
    const selectedPlanInfo = computed(() => {
      if (!reportForm.value.weekly_plan_id) return null
      return availablePlans.value.find(p => p.id === reportForm.value.weekly_plan_id)
    })



    // View linked plan (navigate to plan details)
    const viewLinkedPlan = async (report) => {
      if (!report.weekly_plan_id) return
      
      try {
        // Load the plan details if not already loaded
        if (!availablePlans.value.find(p => p.id === report.weekly_plan_id)) {
          const response = await axios.get(`/api/plans/weekly/${report.weekly_plan_id}`, {
            headers: { Authorization: `Bearer ${authStore.token}` }
          })
          
          ElMessageBox.alert(
            `<div style="line-height: 1.8;">
              <p><strong>计划标题：</strong>${response.data.title}</p>
              <p><strong>描述：</strong>${response.data.description || '无'}</p>
              <p><strong>目标：</strong>${response.data.objectives || '无'}</p>
              <p><strong>状态：</strong>${getStatusText(response.data.status)}</p>
            </div>`,
            '关联计划详情',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '关闭'
            }
          )
        } else {
          const plan = availablePlans.value.find(p => p.id === report.weekly_plan_id)
          ElMessageBox.alert(
            `<div style="line-height: 1.8;">
              <p><strong>计划标题：</strong>${plan.title}</p>
              <p><strong>描述：</strong>${plan.description || '无'}</p>
              <p><strong>目标：</strong>${plan.objectives || '无'}</p>
              <p><strong>状态：</strong>${getStatusText(plan.status)}</p>
            </div>`,
            '关联计划详情',
            {
              dangerouslyUseHTMLString: true,
              confirmButtonText: '关闭'
            }
          )
        }
      } catch (error) {
        console.error('获取计划详情失败:', error)
        ElMessage.error('获取关联计划详情失败')
      }
    }

    // Get week of month from date
    function getWeekOfMonth(date) {
      const firstDayOfMonth = new Date(date.getFullYear(), date.getMonth(), 1)
      const dayOfMonth = date.getDate()
      const firstDayWeekday = firstDayOfMonth.getDay()
      return Math.ceil((dayOfMonth + firstDayWeekday) / 7)
    }

    // Handle date picker change
    const handleDateChange = (val) => {
      if (val) {
        const selectedDate = new Date(val)
        reportForm.value.year = selectedDate.getFullYear()
        reportForm.value.month = selectedDate.getMonth() + 1
        reportForm.value.week = getWeekOfMonth(selectedDate)
      }
    }
    
    const fetchWeeklyReports = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/reports/weekly', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        weeklyReports.value = response.data
      } catch (error) {
        ElMessage.error('获取周报失败')
      } finally {
        loading.value = false
      }
    }

    // Load available plans for the selected week
    const loadAvailablePlans = async () => {
      if (loadingPlans.value) return
      
      loadingPlans.value = true
      try {
        const { year, month, week } = reportForm.value
        const response = await axios.get('/api/reports/weekly/available-plans', {
          params: { year, month, week },
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        availablePlans.value = response.data
        console.log(`加载了 ${availablePlans.value.length} 个可关联的周计划`)
      } catch (error) {
        console.error('加载可关联计划失败:', error)
        ElMessage.error('获取可关联计划失败')
      } finally {
        loadingPlans.value = false
      }
    }

    // Get status text
    const getStatusText = (status) => {
      const statusMap = {
        'pending': '待开始',
        'in_progress': '进行中',
        'completed': '已完成',
        'cancelled': '已取消'
      }
      return statusMap[status] || status
    }

    const openCreateDialog = () => {
      isEdit.value = false
      editingId.value = null
      resetForm()
      reportDate.value = new Date()
      showDatePicker.value = false
      showCreateDialog.value = true
    }

    const editReport = (report) => {
      isEdit.value = true
      editingId.value = report.id
      reportForm.value = {
        year: report.year,
        month: report.month,
        week: report.week,
        achievements: report.achievements,
        challenges: report.challenges,
        next_week_plan: report.next_week_plan
      }
      // Set the date picker to the report's date
      const firstDayOfMonth = new Date(report.year, report.month - 1, 1)
      const firstDayWeekday = firstDayOfMonth.getDay()
      const dayOfMonth = (report.week - 1) * 7 + (7 - firstDayWeekday)
      reportDate.value = new Date(report.year, report.month - 1, dayOfMonth)
      showCreateDialog.value = true
    }
    
    const submitReport = async () => {
      if (!reportFormRef.value) return
      
      await reportFormRef.value.validate(async (valid) => {
        if (valid) {
          submitting.value = true
          try {
            if (isEdit.value) {
              await axios.put(`/api/reports/weekly/${editingId.value}`, reportForm.value, {
                headers: { Authorization: `Bearer ${authStore.token}` }
              })
              ElMessage.success('周报更新成功')
            } else {
              const response = await axios.post('/api/reports/weekly', reportForm.value, {
                headers: { Authorization: `Bearer ${authStore.token}` }
              })
              ElMessage.success('周报提交成功')
              if (response.data.highlights) {
                ElMessage.info(`AI生成的工作亮点: ${response.data.highlights}`)
              }
            }
            
            showCreateDialog.value = false
            resetForm()
            fetchWeeklyReports()
          } catch (error) {
            ElMessage.error(isEdit.value ? '更新失败' : '提交失败')
          } finally {
            submitting.value = false
          }
        }
      })
    }

    const deleteReport = async (report) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除${report.year}年${report.month}月第${report.week}周的周报吗？此操作不可恢复。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await axios.delete(`/api/reports/weekly/${report.id}`, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        ElMessage.success('删除成功')
        fetchWeeklyReports()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const batchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedReports.value.length} 个周报吗？此操作不可恢复。`,
          '确认批量删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        const deletePromises = selectedReports.value.map(id => 
          axios.delete(`/api/reports/weekly/${id}`, {
            headers: { Authorization: `Bearer ${authStore.token}` }
          })
        )
        
        await Promise.all(deletePromises)
        ElMessage.success(`成功删除 ${selectedReports.value.length} 个周报`)
        selectedReports.value = []
        fetchWeeklyReports()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const toggleSelection = (id) => {
      const index = selectedReports.value.indexOf(id)
      if (index === -1) {
        selectedReports.value.push(id)
      } else {
        selectedReports.value.splice(index, 1)
      }
    }

    const toggleSelectAll = () => {
      if (selectedReports.value.length === weeklyReports.value.length && weeklyReports.value.length > 0) {
        selectedReports.value = []
      } else {
        selectedReports.value = weeklyReports.value.map(report => report.id)
      }
    }
    
    const viewReport = (report) => {
      selectedReport.value = report
      showDetailsDialog.value = true
    }
    
    const resetForm = () => {
      reportForm.value = {
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        week: Math.ceil(new Date().getDate() / 7),
        achievements: '',
        challenges: '',
        next_week_plan: '',
        weekly_plan_id: null
      }
      availablePlans.value = []
    }
    
    const formatDate = (date) => {
      return new Date(date).toLocaleString('zh-CN')
    }

    const generateAISummary = async () => {
      if (!aiSummaryForm.value.workContent.trim()) {
        ElMessage.error('请输入工作内容')
        return
      }

      generatingSummary.value = true
      try {
        const response = await axios.post('/api/ai-suggestions/summary-generation', {
          type: 'weekly',
          content: aiSummaryForm.value.workContent,
          timeframe: aiSummaryForm.value.timeframe
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        const { summary, highlights } = response.data
        const highlightsText = Array.isArray(highlights) ? highlights.join('\n') : highlights

        ElMessage.success('AI总结生成成功')
        ElMessage.info({
          message: `AI总结（约400字）：\n\n${summary}\n\n核心亮点：\n${highlightsText}`,
          duration: 15000,
          showClose: true
        })

        showAISummaryDialog.value = false

      } catch (error) {
        console.error('AI总结生成错误:', error)
        if (error.response) {
          ElMessage.error(`AI总结生成失败: ${error.response.data.error || '服务器错误'}`)
        } else if (error.request) {
          ElMessage.error('网络连接失败，请检查网络连接')
        } else {
          ElMessage.error('AI总结生成失败，请稍后重试')
        }
      } finally {
        generatingSummary.value = false
      }
    }

    const generateSummaryForReport = async (report) => {
      // Create a unique loading key for this report
      const loadingKey = `generating_${report.id}`
      
      try {
        // Show loading message
        const loadingMessage = ElMessage({
          message: '正在生成AI总结...',
          type: 'info',
          duration: 0,
          iconClass: 'el-icon-loading'
        })

        const content = `本周成就：${report.achievements}\n遇到挑战：${report.challenges}\n下周计划：${report.next_week_plan}`
        
        const response = await axios.post('/api/ai-suggestions/summary-generation', {
          type: 'weekly',
          content: content,
          timeframe: `${report.year}年${report.month}月第${report.week}周`
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        // Close loading message
        loadingMessage.close()

        const { summary, highlights } = response.data
        const highlightsText = Array.isArray(highlights) ? highlights.join('\n') : highlights

        await axios.put(`/api/reports/weekly/${report.id}`, {
          summary: summary,
          highlights: highlightsText
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        // Update local data
        report.summary = summary
        report.highlights = highlightsText
        
        // Update the report in the weeklyReports array
        const reportIndex = weeklyReports.value.findIndex(r => r.id === report.id)
        if (reportIndex !== -1) {
          weeklyReports.value[reportIndex].summary = summary
          weeklyReports.value[reportIndex].highlights = highlightsText
        }
        
        ElMessage.success('AI总结生成并保存成功')
        
      } catch (error) {
        console.error('AI总结生成错误:', error)
        if (error.response) {
          ElMessage.error(`AI总结生成失败: ${error.response.data.error || '服务器错误'}`)
        } else if (error.request) {
          ElMessage.error('网络连接失败，请检查网络连接')
        } else {
          ElMessage.error('AI总结生成失败，请稍后重试')
        }
      }
    }
    
    onMounted(() => {
      fetchWeeklyReports()
    })
    
    return {
      weeklyReports,
      selectedReports,
      loading,
      showCreateDialog,
      showDetailsDialog,
      showAISummaryDialog,
      selectedReport,
      submitting,
      generatingSummary,
      isEdit,
      editingId,
      reportDate,
      showDatePicker,
      availablePlans,
      loadingPlans,
      selectedPlanInfo,
      reportForm,
      aiSummaryForm,
      reportFormRef,
      rules,
      loadAvailablePlans,
      getStatusText,
      viewLinkedPlan,
      handleDateChange,
      openCreateDialog,
      editReport,
      submitReport,
      deleteReport,
      batchDelete,
      toggleSelection,
      toggleSelectAll,
      viewReport,
      generateAISummary,
      generateSummaryForReport,
      formatDate
    }
  }
}
</script>

<style scoped>
.weekly-reports {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header h3 {
  margin: 0;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.loading-container {
  padding: 20px;
}

.empty-state {
  padding: 40px 0;
}

/* Card Grid Styles */
.report-grid {
  margin-top: 20px;
}

.report-card {
  margin-bottom: 20px;
  transition: all 0.3s ease;
  border: 1px solid #ebeef5;
  border-radius: 12px;
  overflow: hidden;
  cursor: pointer;
  position: relative;
}

.report-card.is-selected {
  border-color: #409eff;
  background-color: #ecf5ff;
}

.report-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 10px;
}

.report-date {
  font-weight: 600;
  font-size: 1.05em;
  color: #2c3e50;
}

.card-content {
  padding: 10px 0;
}

.report-section {
  margin-bottom: 12px;
}

.section-label {
  font-size: 0.85em;
  color: #909399;
  margin-bottom: 4px;
  display: flex;
  align-items: center;
  gap: 4px;
}

.section-text {
  font-size: 0.95em;
  color: #606266;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.section-text.empty {
  color: #c0c4cc;
  font-style: italic;
}

.ai-highlights {
  background: linear-gradient(to right bottom, #f0f9ff, #e0f2fe);
  padding: 10px;
  border-radius: 8px;
  border: 1px solid #bae6fd;
}

.ai-highlights .section-label {
  color: #0284c7;
}

.ai-highlights .section-text {
  color: #334155;
}

.report-meta {
  margin-top: 15px;
  padding-top: 10px;
  border-top: 1px solid #ebeef5;
  font-size: 0.85em;
  color: #909399;
  text-align: right;
}

/* Linked Plan Styles */
.linked-plan {
  background: linear-gradient(135deg, #e0f2fe 0%, #bae6fd 100%);
  border-left: 3px solid #0284c7;
  cursor: default;
}

.linked-plan .section-label {
  color: #075985;
}

.plan-link {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px 12px;
  background: white;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  border: 1px solid #e0f2fe;
}

.plan-link:hover {
  background: #f0f9ff;
  border-color: #0284c7;
  transform: translateX(2px);
  box-shadow: 0 2px 8px rgba(2, 132, 199, 0.15);
}

.plan-info {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
}

.plan-icon {
  color: #0284c7;
  font-size: 16px;
}

.plan-title {
  color: #0c4a6e;
  font-size: 14px;
  font-weight: 500;
}

.arrow-icon {
  color: #64748b;
  font-size: 14px;
  transition: transform 0.3s ease;
}

.plan-link:hover .arrow-icon {
  transform: translateX(3px);
  color: #0284c7;
}

/* Enhanced Report Meta */
.report-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
  margin-top: 12px;
}

.meta-left {
  flex: 1;
}

.meta-right {
  display: flex;
  gap: 6px;
}

.card-actions {
  display: flex;
  justify-content: space-between;
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px dashed #e4e7ed;
}

/* Dialog Styles */
.report-content {
  padding: 10px;
}

.report-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.report-time {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

.report-section h4 {
  display: flex;
  align-items: center;
  gap: 8px;
  margin: 0 0 12px 0;
  color: #333;
  font-size: 15px;
}

.section-content {
  line-height: 1.6;
  color: #555;
  white-space: pre-wrap;
  background-color: #f9fafb;
  padding: 12px;
  border-radius: 8px;
}

.ai-section {
  margin-top: 32px;
  background: linear-gradient(to right bottom, #f0f9ff, #e0f2fe);
  padding: 20px;
  border-radius: 12px;
  border: 1px solid #bae6fd;
}

.ai-section h4 {
  color: #0284c7;
}

.ai-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.ai-summary p {
  margin: 8px 0 0 0;
  line-height: 1.6;
  color: #334155;
}

.ai-highlights .highlight-text {
  margin-top: 8px;
  white-space: pre-wrap;
  color: #334155;
  line-height: 1.6;
}

/* Plan Preview Styles */
.plan-preview {
  margin-top: 12px;
  padding: 12px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 8px;
  border: 1px solid #bae6fd;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 10px;
  font-weight: 600;
  color: #0284c7;
  font-size: 13px;
}

.preview-content {
  font-size: 13px;
  color: #334155;
  line-height: 1.6;
}

.preview-content p {
  margin: 6px 0;
}

.preview-content strong {
  color: #0c4a6e;
}

/* Modern Dialog Styles */
.modern-dialog :deep(.el-dialog__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px 24px;
  margin: 0;
}

.modern-dialog :deep(.el-dialog__title) {
  color: white;
  font-size: 18px;
  font-weight: 600;
}

.modern-dialog :deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

.modern-dialog :deep(.el-dialog__body) {
  padding: 24px;
  background-color: #f8f9fa;
}

.modern-dialog :deep(.el-dialog__footer) {
  padding: 16px 24px;
  background-color: #fff;
  border-top: 1px solid #e5e7eb;
}

.modern-form {
  max-height: 600px;
  overflow-y: auto;
  padding-right: 8px;
}

.modern-form::-webkit-scrollbar {
  width: 6px;
}

.modern-form::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 10px;
}

.modern-form::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 10px;
}

.modern-form::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.form-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.form-section:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transform: translateY(-2px);
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 2px solid #f0f0f0;
}

.section-header span {
  font-size: 15px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.header-icon {
  font-size: 20px;
  color: #667eea;
}

.header-icon.success {
  color: #10b981;
}

.header-icon.warning {
  color: #f59e0b;
}

.header-icon.primary {
  color: #3b82f6;
}

.auto-date-display {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: linear-gradient(135deg, #e0e7ff 0%, #ede9fe 100%);
  border-radius: 8px;
  border: 2px solid #c7d2fe;
}

.date-info {
  display: flex;
  align-items: center;
  gap: 8px;
  color: #5b21b6;
}

.date-info .el-icon {
  font-size: 18px;
}

.date-text {
  font-size: 15px;
  font-weight: 600;
}

.date-explain {
  margin-top: 8px;
  padding: 8px 12px;
  background: linear-gradient(135deg, #e0e7ff 0%, #ede9fe 100%);
  border-radius: 6px;
  color: #5b21b6;
  font-size: 13px;
  font-weight: 500;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.modern-form :deep(.el-form-item__label) {
  font-weight: 500;
  color: #374151;
  margin-bottom: 8px;
}

.modern-form :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 1.5px solid #e5e7eb;
  transition: all 0.3s ease;
  font-family: inherit;
  line-height: 1.6;
}

.modern-form :deep(.el-textarea__inner:focus) {
  border-color: #667eea;
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}

.modern-form :deep(.el-date-editor) {
  border-radius: 8px;
  border: 1.5px solid #e5e7eb;
}

.modern-form :deep(.el-date-editor:hover),
.modern-form :deep(.el-date-editor.is-active) {
  border-color: #667eea;
}

.modern-form :deep(.el-tag) {
  margin-left: auto;
  border-radius: 4px;
}
</style>

